from django.shortcuts import render
from django.views import View
from django.http import HttpResponse, JsonResponse
import random
from meiduo_mall.settings.dev import logger
from django_redis import get_redis_connection
from celery_tasks.sms.tasks import send_sms_code


class SMSCodeView(View):
    def get(self, request, mobile):
        # 接受验证码 pid
        uuid = request.GET.get("image_code_id")
        image_code = request.GET.get("image_code")

        # try:
        #     # 读取图形验证吗
        #
        #     image_code_client = get_redis_connection("verify_image_code")
        #     redis_img_code = image_code_client.get("image_%s" % uuid)
        #
        #     # 校验图片验证码的正确性--redis_image_code 一样; null 过期了, 不一致,写错了
        #     if not redis_img_code:
        #         return JsonResponse({"code":"4001", "errmsg":"图形验证码失效"})
        #     if image_code.lower() != redis_img_code.decode().lower():
        #         return JsonResponse({"code": "4001", "errmsg": "图形验证码错误"})
        #
        #     # 校验后删除
        #     image_code_client.delete("image_%s" % uuid)
        # except Exception as e:
        #     logger.error(e)
        # 创建 验证码

        sms_redis = get_redis_connection("sms_code")
        send_flag = sms_redis.get('send_flag_%s' % mobile)

        if send_flag:
            return JsonResponse({'code': '4002', 'errmsg': '发送短信太频繁了'})

        sms_code = random.randint(100000, 999999)

        # 创建Redis管道
        p1 = sms_redis.pipeline()
        try:
            # # 将Redis请求添加到队列
            p1.setex("send_flag_%s" % mobile, 30, sms_code)
            p1.setex("sms_%s" % mobile, 30, sms_code)
            # 执行请求
            p1.execute()
        except Exception as e:
            logger.error(e)


        # CCP().send_template_sms(mobile, [sms_code,5],1)
        # 容联云发送短信---celery异步发送
        send_sms_code.delay(mobile, sms_code)
        print(sms_code)
        return JsonResponse({"code": "0", "errmsg": "发送短信成功"})


class ImageCodeView(View):
    def get(self, request, uuid):
        # 生成验证码
        from libs.captcha.captcha import captcha
        text, image = captcha.generate_captcha()
        # 保存到redis数据库
        from django_redis import get_redis_connection
        image_codes = get_redis_connection("verify_image_code")
        image_codes.setex("image_%s" % uuid, 3000, text)
        # 返回验证码
        return HttpResponse(image, content_type="image/jpeg")